package org.example.springboot137.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtil {
    //阿里云的服务地址
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    //id号
    private String accessKeyId = "LTAI5tFS6TCFmQZyTzPubbhz";
    //密码
    private String accessKeySecret = "uFhiuuIJITi1oFTGod7QtrAcXZorBC";
    //用户名
    private String bucketName = "lzy-20241031";

    /*private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String accessKeyId = "LTAI5tFS6TCFmQZyTzPubbhz";
    private String accessKeySecret = "uFhiuuIJITi1oFTGod7QtrAcXZorBC";
    private String bucketName = "lzy-20241031";*/

    /**
     *
     * @param file 上传文件要的文件
     * @return 文件上传后所存放的响应
     */
    public String upload(MultipartFile file) throws IOException {
        //取得上传文件的输入流
        //得到上传文件的流
        InputStream inputStream = file.getInputStream();
        //得到文件流
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename = " + originalFilename);
        //截取文件名 ，没有后缀
        String suffix = file.getOriginalFilename().substring(originalFilename.lastIndexOf("."));
        //uuid 全球唯一 拼接新的文件名
        String fileName=UUID.randomUUID().toString()+suffix;
        //得到阿里上传工具类上传文件的工具对象
        OSS build = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //调用上传的方法
        build.putObject(bucketName, fileName, inputStream);
        //关闭
        build.shutdown();
        //拼接好存放文件的地址 https://oss-cn-hangzhou.aliyuncs.com
        String fileUrl="";
        String fileF= endpoint.substring(0, endpoint.indexOf("//"));
        String file1=endpoint.substring(endpoint.lastIndexOf("//")+2, endpoint.length());
        fileUrl=fileF+"//"+bucketName+"."+file1+"/"+fileName;
        System.out.println("fileUrl=" + fileUrl);
        /*String[] url=endpoint.split("//");
        fileUrl=url[0]+"//"+bucketName+"."+url+"/"+fileName;*/
       return fileUrl;
    }
}
